#include "Action_Transfer_Cf.h"
#include "Spi_Dev_Management/Spi_Buffer_Manager.h"
#include "Utilities/Utilities.h"
#include <thread>

Action_Transfer_Cf::Action_Transfer_Cf(ISpi_Dev* dev, Ibuffer_User_Register* buffer_register)
    : its_spi_dev(dev), its_mcu_2_soc_data_buffer(buffer_register->register_whole_in_buffer(Buffer_Id::SOC_IN_CF))
    , its_soc_2_mcu_data_buffer(buffer_register->register_whole_out_buffer(Buffer_Id::SOC_OUT_CF)), its_tx(nullptr), its_rx(nullptr)
    , its_rx_cb(nullptr)
{
    its_tx = new uint8_t[CF_DATA_SIZE];
    its_rx = new uint8_t[CF_DATA_SIZE];
}

Action_Transfer_Cf::~Action_Transfer_Cf()
{
    delete[] its_tx;
    delete[] its_rx;
    its_tx = nullptr;
    its_rx = nullptr;
}

void Action_Transfer_Cf::execute()
{
    auto timestamp = Utility::getTimestampUs();
    if(its_spi_dev)
    {
        its_soc_2_mcu_data_buffer->copy_full_buffer(its_tx, CF_DATA_SIZE);
        its_spi_dev->transfer(its_tx, its_rx, CF_DATA_SIZE);
        its_mcu_2_soc_data_buffer->copy_full_buffer(its_rx, CF_DATA_SIZE);
        if(its_rx_cb)
        {
            its_rx_cb(its_mcu_2_soc_data_buffer);
        }
    }
    
    while(Utility::getTimestampUs() - timestamp < Time_Interval) 
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

}

void Action_Transfer_Cf::register_rx_callback(std::function<void(const Soc_In_Data_Buffer*)> cb)
{
    its_rx_cb = cb;
}
